package com.tianji.learning.service.impl;

import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.common.utils.BooleanUtils;
import com.tianji.common.utils.DateUtils;
import com.tianji.common.utils.ObjectUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.constans.RedisConstants;
import com.tianji.learning.domain.po.PointsRecord;
import com.tianji.learning.domain.vo.SignResultVO;
import com.tianji.learning.mapper.PointsRecordMapper;
import com.tianji.learning.mq.message.SignMessage;
import com.tianji.learning.service.SignRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

import static com.tianji.common.constants.MqConstants.Exchange.LEARNING_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.SIGN_IN;

/**
 * <p>
 * 学习积分记录，每个月底清零 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-11-17
 */
@Service
@RequiredArgsConstructor
public class SignRecordServiceImpl extends ServiceImpl<PointsRecordMapper, PointsRecord> implements SignRecordService {

    private final StringRedisTemplate redisTemplate;
    private final RabbitMqHelper mqHelper;

    @Override
    public SignResultVO sign() {
        // 1、签到
        // 1.1、获取签到key
        String key = getSignKey();

        // 1.2、计算offset值
        long offset = LocalDate.now().getDayOfMonth() - 1;

        // 1.3、查询key是否存在
        Long keyCount = redisTemplate.countExistingKeys(Collections.singleton(key));
        boolean keyExists = false;
        if(ObjectUtils.isNotEmpty(keyCount) && keyCount > 0){
            keyExists = true;
        }

        // 1.4、签到并校验是否重复签到（核心）
        Boolean exists = redisTemplate.opsForValue().setBit(key, offset, true);
        if(BooleanUtils.isTrue(exists)){
            throw new BizIllegalException("不允许重复签到！");
        }

        // 1.5、如果key之前并不存在，证明是本月第一次签到，需要设置过期时间
        if(!keyExists){
            LocalDateTime beginTime = LocalDateTime.now();  //  ==》  2024-12-01 00:00:00
            LocalDateTime endTime = DateUtils.getMonthBeginTime(LocalDate.now().plusMonths(1));
            Duration between = DateUtils.between(beginTime, endTime);
            redisTemplate.expire(key,between);
        }

        // 2、计算连续签到天数
        int signDays = countSignDays(key);
        // 3、计算签到奖励积分
        int rewardPoints = computeRewardPoints(signDays);

        // 4、构建Vo
        SignResultVO vo = new SignResultVO();
        vo.setSignDays(signDays);
        vo.setRewardPoints(rewardPoints);

        // 5、发送保存积分明细的消息 (埋点)
        try {
            mqHelper.send(LEARNING_EXCHANGE, SIGN_IN, SignMessage.of(UserContext.getUser(),vo.totalPoints()));
        } catch (Exception e) {
            log.error("签到发送新增积分消息失败：{}", e);
        }

        // 6、返回vo
        return vo;
    }

    /**
     * 2、查询当月截止到当天的签到记录（Day7 - 课堂2）
     *
     * @return
     */
    @Override
    public Byte[] querySignRecords() {
        // 1、获取签到key
        String key = getSignKey();

        // 2、通过bitfield命令获取本月从第一天到今天为止的所有签到记录
        int dayOfMonth = LocalDate.now().getDayOfMonth();
        List<Long> result = redisTemplate.opsForValue().bitField(key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0)
        );
        if(ObjectUtils.isEmpty(result)){
            return new Byte[]{};
        }
        int signResult = result.get(0).intValue();

        // 3、循环每一天的签到记录，赋值给数组
        Byte[] arr = new Byte[dayOfMonth];
        int pos = dayOfMonth - 1;
        while (pos >= 0){
            arr[pos--] = (byte)(signResult & 1);
            signResult >>>= 1;
        }
        return arr;
    }


    private int computeRewardPoints(int signDays) {
        switch (signDays){
            case 7:
                return 10;
            case 14:
                return 20;
            case 28:
                return 40;
            default:
                return 0;
        }
    }

    private int countSignDays(String key) {
        // 1、通过bitfield命令获取本月从第一天到今天为止的所有签到记录
        int dayOfMonth = LocalDate.now().getDayOfMonth();
        List<Long> result = redisTemplate.opsForValue().bitField(key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0)
        );
        if(ObjectUtils.isEmpty(result)){
            return 0;
        }
        int signResult = result.get(0).intValue();

        // 2、定义一个计数器，用来记录连续签到天数
        int days = 0;

        // 3、用签到查询结果不断跟1做与运算，判断是否等于1
        while ((signResult & 1) == 1){
            // 3.1、连续签到天数 +1
            days++;
            // 3.2、签到结果无符号右移一位
            signResult >>>= 1;
        }
        return days;
    }

    private String getSignKey() {
        Long userId = UserContext.getUser();

        String dateStr = LocalDate.now().format(DateUtils.SIGN_DATE_SUFFIX_FORMATTER);

        String key = RedisConstants.SIGN_RECORD_KEY_PREFIX + userId + dateStr;;
        return key;
    }
}
